package com.cy.tempflinkcdc.util;

import com.jcraft.jsch.*;
import org.apache.commons.net.ftp.FTPClient;
import java.io.*;
import java.util.Objects;
import org.springframework.stereotype.Component;

@Component
public class FTPUtils {


    /**
     * 将文件上传到 FTP 服务器
     * @param
     */
    public static void doPostFile(String localFilePath,String server,int port,String username,String password) {


        File file = new File(localFilePath);
        String fileName = file.getName();
        String remoteFilePath = fileName;

        if (Objects.equals(port, 22)) {
            //      Sftp
            JSch jsch = new JSch();
            Session session = null;
            ChannelSftp channel = null;

            try {
                session = jsch.getSession(username, server, port);
                session.setPassword(password);
                session.setConfig("StrictHostKeyChecking", "no");
                session.connect();

                channel = (ChannelSftp) session.openChannel("sftp");
                channel.connect();

                channel.put(localFilePath, new File(localFilePath).getName());
            } catch (JSchException | SftpException e) {
                e.printStackTrace();
            }  finally {
                if (channel != null) channel.disconnect();
                if (session != null) session.disconnect();
            }
        }else {
            //    ftp
            try {

                FTPClient ftpClient = new FTPClient();
                ftpClient.connect(server, port);
                ftpClient.login(username, password);

                // 设置传输模式为二进制
                ftpClient.setFileType(FTPClient.BINARY_FILE_TYPE);

                // 上传文件
                try (FileInputStream fis = new FileInputStream(localFilePath)) {
                    ftpClient.storeFile(remoteFilePath, fis);
                }

                ftpClient.logout();
                ftpClient.disconnect();

            } catch (IOException e) {
                e.printStackTrace();
            }

        }



    }

}
